/**
 * ---------------------------------- 功能说明：系统JS方法公用类 
 * 功能说明： 
 * myformatter(date)：Jquery EasyUI日期组件进行foramt设置 
 * myparser(date) ：Jquery EasyUI日期组件进行foramt设置
 * showWindow(options) ：弹出提示框 
 * closeWindow() ：关闭提示框 
 * clearForm(formIm) ：重置表单
 * showMsg(msg) ：信息弹出框(自动) 自动弹出 自动消失 
 * showMsgInfo(msg) ：信息弹出框 带遮罩背景的提示信息框
 * checkAll(source, name) ：选择所有的checkbox 
 * getCkValByName(cName) ：通过checkbox名称获得被选中的值(用","分隔) 
 * isEdit(rows) ：如果没选或多选记录都返回false,否则返回true（编辑）
 * isView(rows) ：如果没选或多选记录都返回false,否则返回true（查看） 
 * isDel(rows) ：如果没选或多选记录都返回false,否则返回true（删除） 
 * setFormReadOnly(formId) ：设置表单里的文本框为只读
 * ltrim(arg) ：删除左空格 
 * rtrim(arg) ：删除右空格 
 * trim(arg) ：删除空格 
 * isEmpty(v, allowBlank) ：判断是否是空 
 * isArray(arg) ：判断是否为数组 
 * formatDate(dateStr) ：对日期进行格式化 
 * getWidth(percent) ：自动调整表格列宽度 
 * sCurDate(date) ：JS 判断日期是否是当日 
 * returnWeekName(date) ：JS 根据日期返回星期
 * getPageLanguage() ：获取浏览器语言 
 * getBrowser() ：获取浏览器类型 IE FF 
 * messageFormat(string): 主要用于I18N的消息（参数）格式化 
 * getQueryString(name, srchString)：获取URL中参数的值
 * removeFromArray(tempArray,obj)：从数据组对象中移除指定对象值
 * WHUtil.stringifyJSON(value)：转换对象为JSON字符串
 * Array.prototype.indexOfArray(substr,start)：从指定数组对象中获取指定值的索引号
 * WHUtil.getCookie(cName):获取指定cookie名
 * WHUtil.setCookie(cName,value,expire):设置cookie值及过期时间（单位：天）
 * WHUtil.checkCookie(cName):检测指定cookie名是否存在
 *  
 * 修复时间：2013-4-7
 * ----------------------------------
 */
function WHUtil() {
};
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
WHUtil.string2Date = function(dateTimeString){
	// 时间格式：yyyy-MM-dd HH:mm:ss
	if(dateTimeString){
		var dateTime = dateTimeString.split(/\-|\s/);
		return new Date(Date.parse(dateTime.slice(0,3).join("/")+" "+dateTime[3]));
	}
	return newDate();
};
/**
 * Jquery EasyUI日期组件进行foramt设置 格式"xxxx-x-x"
 */
function myformatter(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}

function xgFormatter(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	var hh = date.getHours();	 	// hour
	var mm = date.getMinutes(); 	// minute
	var ss = date.getSeconds(); 	// second
	var showTime = " " + getShow(hh) + ":"+ getShow(mm)+ ":" + getShow(ss);
	return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + showTime;
}
function xgParser(s) {	
	if (!s)
		return new Date();
	var dt = s.split(/\-|\s/);
	var time = Date.parse(dt.slice(0,3).join("/")+" "+dt[3]);
	return new Date(time);
	
	/*var ss = s.split(" ");
	var ss1 = ss[0].split("/");
	var ss2 = ss[1].split(":");
	
	var y = parseInt(ss1[2], 10);
	var m = parseInt(ss1[0], 10);
	var d = parseInt(ss1[1], 10);
	
	var h = parseInt(ss2[0], 10);
	var f = parseInt(ss2[1], 10);
	var si = parseInt(ss2[2], 10);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d) && !isNaN(h) && !isNaN(f) && !isNaN(si)) {
		var newTime = new Date(y,m,d,h,f,si);
		return newTime;
	} else {
		return new Date();
	}*/
}

function xgFormatterTime(date) 
{//格式类似于：2013-06-04 11:24:22
	
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	
	var hh = date.getHours();	 	// hour
	var mm = date.getMinutes(); 	// minute
	var ss = date.getSeconds(); 	// second
	var showTime = " " + getShow(hh) + ":"+ getShow(mm)+ ":" + getShow(ss);
	return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + showTime;
}

// 打开/选择tab标签（tabConf:{type,id,src,tabName,needRefresh}）
function addMainFramTab(tabConf){
	var tabIframe = '<iframe id="frame'+tabConf.type+tabConf.id+'" scrolling="auto" width="100%"  frameborder="0" src="'+tabConf.src+'" style="height:100%;" scrolling="no"></iframe>';
	var tabName = tabConf.tabName;
	var mainFrame = window.parent.$('#mainTab');
	if (mainFrame.tabs('exists', tabName)){
		mainFrame.tabs('select', tabName);
		if(tabConf.needRefresh){
			var tab = mainFrame.tabs('getTab',tabName);
			if(tab){
				mainFrame.tabs('update',{tab:tab,options:{
					title:tabName,
					content: tabIframe,
					closable: true,
					fit:true,
					border:false,
					plain:true					
				}});
			}
		}
	}else{
		mainFrame.tabs('add',{
			title:tabName,
			content: tabIframe,
			closable: true,
			fit:true,
			border:false,
			plain:true
		});
	}
}

function updateMainFramTab(tabConf){
	var tabIframe = '<iframe id="frame'+tabConf.type+tabConf.id+'" scrolling="auto" width="100%"  frameborder="0" src="'+tabConf.src+'" style="height:100%;" scrolling="no"></iframe>';
	var tabName = tabConf.tabName;
	var mainFrame = window.parent.$('#mainTab');
	if (mainFrame.tabs('exists', tabName)){
		mainFrame.tabs('select', tabName);
		updateTab(tabIframe);
	}else{
		mainFrame.tabs('add',{
			title:tabName,
			content: tabIframe,
			closable: true,
			fit:true,
			border:false,
			plain:true
		});
	}
}

function updateTab(show) {
	var mainFrame = window.parent.$('#mainTab');
	var tab = mainFrame.tabs('getSelected');
	mainFrame.tabs('update', {
        tab: tab,
		options: {
			content: show
	        }
	    }); 
    tab.panel('refresh');
}

function getShow(d) {
	return d<10?('0'+d):d;
}
/**
 * Jquery 日期组件进行foramt设置 格式"xxxx-x-x"
 * 
 * @since 1.0
 */
function myparser(s) {
	if (!s)
		return new Date();
	var ss = s.split('-');
	var y = parseInt(ss[0], 10);
	var m = parseInt(ss[1], 10);
	var d = parseInt(ss[2], 10);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
		return new Date(y, m - 1, d);
	} else {
		return new Date();
	}
}

/**
 * 弹出提示框
 * 
 * @since 1.0
 */
function showWindow(options) {
	// options.top = ($(window).height() - 270) * 0.5;
	// options.left = ($(window).width() - 350) * 0.5-170;
	if(options.href != ''){
		options.href = webBasePath + options.href;
	}
	options.minimizable = false;
	options.maximizable = false;
	options.collapsible = false;
	options.loadingMessage = I18N.msg_loading;
	$("#MyPopWindow").window(options);
	// $('#MyPopWindow').window('refresh');
	// $('#MyPopWindow').window('open');
}
/**
 * 关闭弹出框
 * 
 * @since 1.0
 */
function closeWindow() {
	$('.validatebox-tip').remove(); 
	$("#MyPopWindow").window('close');
	// $("#MyPopWindow").window('destroy');
}
function showDialog(options) {
	if(options.href != ''){
		options.href = webBasePath + options.href;
	}
	// $("#MyDialogIframe").src = options.href; 
	$('#MyDialog').dialog(options);
}

function closeDialog() {
	$('.validatebox-tip').remove(); 
	$('#MyDialog').dialog("close");
}
/**
 * 重置表单
 * 
 * @param formId
 *            表单ID
 * @since 1.0
 */
function clearForm(formId) {
	$('#' + formId).form('clear');
	// $('#'+formId).resetForm();
}
/**
 * 信息弹出框(自动) 自动弹出 自动消失
 * 
 * @param msg
 *            提示消息
 * @since 1.0
 */
function showMsg(msg) {
	if (msg == 'success') {
		msg = I18N.success;
	} else if (msg == 'failure') {
		msg = I18N.failure;
	} else if (msg == 'startSuccess'){
		msg = I18N.startSuccess;
	} else if (msg == 'flowFailure'){
		msg = I18N.flowFailure;
	} else if (msg == "flowException"){
		msg = I18N.flowException;
	}
	$.messager.show({
		title : I18N.info,
		msg : msg,
		shadow : true,
		timeout : 2000,
		style : {
		// top: ($(window).height() - 180) * 0.5,
		// left: ($(window).width() - 480) * 0.5
		}
	});
}

function showRichMessage(msgCfg){
	$.messager.show({
		title:msgCfg.title,
		msg:msgCfg.content,
		shadow:true,
		timeout:0,
		style:{},
		width:350,
		height:180
	});
	$(".messager-body").attr("style","scroll-y:auto");
}

function getMsg(msg) {
	
	if (msg == 'success') {
		msg = I18N.success;
	} else if (msg == 'failure') {
		msg = I18N.failure;
	} else if (msg == 'startSuccess'){
		msg = I18N.startSuccess;
	} else if (msg == 'flowFailure'){
		msg = I18N.flowFailure;
	}else if (msg == 'notFindPerson'){
		msg = I18N.notFindPerson;
	}else if (msg == 'nextNotFindPerson'){
		msg = I18N.nextNotFindPerson;
	}else if (msg == '1') {
		msg = I18N.success;
	} else if (msg == '0') {
		msg = I18N.failure;
	}else if (msg == '200'){
		msg = I18N.CODE_SUCCESS;
	}else if (msg == '500' || msg == 'CODE_RUNTIME_EXCEPTION'){
		msg = I18N.CODE_RUNTIME_EXCEPTION;
	}else if (msg == '400'){
		msg = I18N.CODE_PARAMETER_EXCEPTION;
	}else if (msg == '503'){
		msg = I18N.startSuccess;
	}else if (msg == '504'){
		msg = I18N.startSuccess;
	}else if (msg == '502'){
		msg = I18N.startSuccess;
	}else if(msg == '31'){
		msg = I18N.CODE_LEVELONEDEPID_ISREQUIRED;
	}else if(msg == '41'){
		msg = I18N.CODE_PROJECTINFOS_INCOMPLETE;
	}else if(msg == '42'){
		msg = I18N.FYBX_BATCHNO_ONECOMPANY;
	}else if(msg == 'NO_NEXT_OPERATOR'){
		msg = I18N.NO_NEXT_OPERATOR;
	}else if(msg == 'NO_NEXT_OPERATOR_701_ESG'){
		msg = I18N.NO_NEXT_OPERATOR_ONE;
	}else if(msg == 'NO_NEXT_OPERATOR_702_ESG'){
		msg = I18N.NO_NEXT_OPERATOR_TWO;
	}else if(msg == 'NO_NEXT_OPERATOR_703_ESG'){
		msg = I18N.NO_NEXT_OPERATOR_THREE;
	}else if(msg == 'NO_NEXT_OPERATOR_801_BUS'){
		msg = I18N.NO_NEXT_OPERATOR_ONE;
	}else if(msg == 'NO_NEXT_OPERATOR_802_BUS'){
		msg = I18N.NO_NEXT_OPERATOR_TWO;
	}else if(msg == 'NO_NEXT_OPERATOR_803_BUS'){
		msg = I18N.NO_NEXT_OPERATOR_THREE;
	}
	
	
	return msg;
}
/**
 * 信息弹出框 带遮罩背景的提示信息框
 * 
 * @param msg
 *            提示消息
 * 
 */
function showMsgInfo(msg) {
	$.messager.alert(I18N.promp, msg, "info");
}

function showErrorWindow(data) {
	$("#errorWindow").dialog({
		title : I18N.info,
		width : 515,
		iconCls : 'icon-error',
		content : data.responseText,
		height : 340
	});
}

function closeErrorDialog() {
	$('#errorWindow').dialog("close");
}
/**
 * 选择所有的checkbox
 * 
 * @param name
 * @since 1.0
 */
function checkAll(source, name) {
	for ( var i = 0; i < document.getElementsByName(name).length; i++) {
		document.getElementsByName(name)[i].checked = source.checked;
	}
}
/**
 * 通过checkbox名称获得被选中的值(用","分隔)
 * 
 * @param checkboxName
 * @return string
 * @since 1.0
 */
function getCkValByName(checkboxName) {
	var checkValues = "";
	var elementArr = document.getElementsByName(checkboxName);
	var size = elementArr.length;
	for ( var i = 0; i < size; i++) {
		var element = elementArr[i];
		if (element.checked) {
			checkValues += element.value + ",";
		}
	}
	if (checkValues != "") {
		checkValues = checkValues.substr(0, checkValues.length - 1);
	}
	return checkValues;
}

/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选中的行
 * @return boolean
 * @since 1.0
 */
function isEdit(rows) {
	if (rows.length == 0) {
		showMsg(I18N.msg_no_sel_edit_record);
		return false;
	} else if (rows.length > 1) {
		showMsg(I18N.msg_single_edit_record);
		return false;
	} else {
		return true;
	}
}
/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选中的行
 * @return boolean
 * @since 1.0
 */
function isExportExcel(rows) {
	if (rows.length == 0) {
		showMsg(I18N.msg_no_sel_export_record);
		return false;
	} else if (rows.length > 1) {
		showMsg(I18N.msg_single_export_record);
		return false;
	} else {
		return true;
	}
}
/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选中的行
 * @return boolean
 * @since 1.0
 */
function isSelectRow(rows) {
	if (rows.length == 0) {
		showMsg(I18N.msg_no_sel_role_record);
		return false;
	} else if (rows.length > 1) {
		showMsg(I18N.msg_single_role_record);
		return false;
	} else {
		return true;
	}
}

/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选中的行
 * @return boolean
 * @since 1.0
 */
function isSelectPrjRow(rows) {
	if (rows.length == 0) {
		showMsg(I18N.showBudgetPrj);
		return false;
	} else if (rows.length > 1) {
		showMsg(I18N.single_showBudgetPrj);
		return false;
	} else {
		return true;
	}
}
/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选择的行数
 * @return boolean
 * @since 1.0
 */
function isView(rows) {
	if (rows.length == 0) {
		showMsg(I18N.msg_no_sel_view_record);
		return false;
	} else if (rows.length > 1) {
		showMsg(I18N.msg_single_view_record);
		return false;
	} else {
		return true;
	}
}

/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选择的行数
 * @return boolean
 * @since 1.0
 */
function isDel(rows) {
	if (rows.length == 0) {
		showMsgInfo(I18N.msg_no_sel_del_record);
		return false;
	} else {
		return true;
	}
}

/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选择的行数
 * @return boolean
 * @since 1.0
 */
function isOff(rows) {
	if (rows.length == 0) {
		showMsg(I18N.msg_del);
		return false;
	} else {
		return true;
	}
}

/**
 * 如果没选或多选记录都返回false,否则返回true
 * 
 * @param rows
 *            选择的行数
 * @param msg
 *            提示信息
 * @return boolean
 * @since 1.0
 */
function isOperMsg(rows, msg) {
	if (rows.length == 0) {
		showMsgInfo(msg);
		return false;
	} else {
		return true;
	}
}
/**
 * 信息弹出框(自动) 自动弹出 自动消失
 * 
 * @param msg
 *            提示消息
 * @since 1.0
 */
function showOperMsg(msg) {
	var showMsgInfo = msg;
	$.messager.show({
		title : I18N.info,
		msg : showMsgInfo,
		shadow : true,
		timeout : 2000,
		style : {
		// top: ($(window).height() - 180) * 0.5,
		// left: ($(window).width() - 480) * 0.5
		}
	});
}
/**
 * 设置表单里的文本框为只读
 * 
 * @return boolean
 * @since 1.0
 */
function setFormReadOnly(formId) {
	var formEl = document.getElementById(formId);
	for ( var i = 0; i < formEl.elements.length; i++) {
		var element = formEl.elements[i];
		if (element.type == 'text') {
			element.readOnly = true;
		}
	}
}
/**
 * 删除左空格
 * 
 * @param arg
 * @return string
 * @since 1.0
 */
function ltrim(arg) {
	return arg.replace(/^\s*/, "");
}

/**
 * 删除右空格
 * 
 * @param name
 * @return string
 * @since 1.0
 */
function rtrim(s) {
	return s.replace(/\s*$/, "");
}

/**
 * 删除左右空格
 * 
 * @param name
 * @return string
 * @since 1.0
 */
function trim(s) {
	return rtrim(ltrim(s));
}

/**
 * 判断是否为空
 * 
 * @param v
 * @param allowBlank
 *            是否允许''为空
 * @return boolean
 * @since 1.0
 */
function isEmpty(v, allowBlank) {
	return v === null || v === undefined || ((isArray(v) && !v.length))
			|| (!allowBlank ? v === '' : false);
}

/**
 * 判断变量是否是数组
 * 
 * @param arg
 * @return boolean
 * @since 1.0
 */
function isArray(arg) {
	if (typeof arg == 'object' && typeof arg.sort == 'function'
			&& typeof arg.length == 'number') {
		return true;
	} else {
		return false;
	}
}

/**
 * 对日期进行格式化
 * 
 * @param dateStr
 *            日期字符串
 * @return 格式后的
 * @since 1.0
 */
function formatDate(dateStr) {
	var dateObject = new Date(dateStr);
	if (isNaN(dateObject)) {
		if (dateStr.length > 10) {
			return dateStr.substr(0, 10);
		} else {
			return dateStr;
		}
	} else {
		var month = dateObject.getMonth() - 0 + 1;
		var day = dateObject.getDate() - 0;
		if (month < 10) {
			month = "0" + month;
		}
		if (day < 10) {
			day = "0" + day;
		}
		return dateObject.getFullYear() + "-" + month + "-" + day;
	}
}
/**
 * 自动调整表格列宽度
 * 
 * @param percent
 *            百分比
 * @return 列宽度百分比
 * @since 1.0
 */
function getWidth(percent) {
	return new Number(document.body.clientWidth * percent); // 这里你可以自己做调整
}
/**
 * JS 判断是否是周末
 * 
 * @param date
 *            日期
 * @return boolean
 * @since 1.0
 */
function isWeekDay(date) {
	var day = date.getDay();
	var arr_week = new Array("7", "1", "2", "3", "4", "5", "6");
	if (arr_week[day] == "6" || arr_week[day] == "7") {
		return true;
	}
	return false;
}
/**
 * JS 判断日期是否是当日
 * 
 * @param date
 *            日期
 * @return boolean
 * @since 1.0
 */
function isCurDate(date) {
	var curDate = new Date();
	if (curDate.getFullYear() == date.getFullYear()
			&& (curDate.getMonth() + 1) == (date.getMonth() + 1)
			&& curDate.getDate() == date.getDate()) {
		return true;
	}
	return false;
}

/*function comptime(date) {
    var d1 = $.fn.datebox.defaults.parser(myformatter(new Date()));
	var d2 = $.fn.datebox.defaults.parser(date);
    if (d2.getTime()==d1.getTime()) {
       return "0";//时间相等
    } else if (d2.getTime()>d1.getTime()) {
    	 return "1";//时间未到
    } else if (d2.getTime()<d1.getTime()) {
    	 return "2";//时间过期
    }

    return "3";
}*/
function comptime(value) {
	var partten=/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
	var startDate = myformatter(new Date());
	var res = startDate.match(partten);
	if(res == null){return true;}
	var arr1 = startDate.split("-");
	var arr2 = value.split("-");
	if(res.length == 5){	
   			if(arr1[0]<arr2[0]){
   				return "1";//时间未到
   			}else if(arr1[0] == arr2[0]){
   				if(arr1[1]<arr2[1]){
   					return "1";//时间未到
   				}else if(arr1[1] == arr2[1]){
   					if(arr1[2]<arr2[2]){
   						return "1";//时间未到
   					}else if(arr1[2]>arr2[2]){
   						return "2"; //时间过期
   					}else if(arr1[2] == arr2[2]){
   						return "0";//时间相等
   					}
   				}else if(arr1[1]>arr2[1]){
   					return "2"; //时间过期
   				}
   			}else if(arr1[0]>arr2[0]){
   				return "2"; //时间过期
   			}
	}
    return "3";
}

/**
 * JS 根据日期返回星期
 * 
 * @param date
 *            日期
 * @return boolean
 * @since 1.0
 */
function returnWeekName(date) {
	var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
	return arr_week[date.getDay()];
}
/**
 * JS 获取浏览器语言
 * @since 1.0
 */
function getPageLanguage() {
	var lang = "";
	var oType = getBrowser();
	switch (oType) {
	case "IE":
		lang = window.navigator.userLanguage;
		break;
	case "FIREFOX":
		lang = window.navigator.language;
		break;
	default:
		lang = window.navigator.language;
		break;
	}
	return lang;
}
/**
 * JS 获取浏览器类型 IE FF
 * @since 1.0
 */
function getBrowser() {
	var oType = "";
	if (navigator.userAgent.indexOf("MSIE") != -1) {
		oType = "IE";
	} else if (navigator.userAgent.indexOf("Firefox") != -1) {
		oType = "FIREFOX";
	}
	return oType;
}
/**
 * JS 显示Loading加载画面
 * 
 * @since 1.0
 */
function ShowLoading() {
	jQuery('#LoadingInfo').showLoading();
}
/**
 * JS 结束Loading加载画面
 * 
 * @since 1.0
 */
function HideLoading() {
	jQuery('#LoadingInfo').hideLoading();
}
/**
 * JS dataGrid数据为空时，提示没有数据
 * 
 * @since 1.0
 */
function showEmptyDataTip(data, gridId) {
	if (data && data.rows && data.rows.length == 0) {
		$("#" + gridId + "_gridBody").empty();
		$("#" + gridId + "_gridBody").html(
				"<div style='height:25px;text-align:center;line-height:25px;'>"
						+ I18N.emptyDataTip + "</div>");
	}
}
function test(f){
	f();
}

/**
 * @param gridId gridID
 * @param gridBtnObj 
 *  例：
 *  在gird的 onLoadSuccess 中调用（最后调用）
 *	var aa = function(){alert("111111");};
 *	var bb = function(){alert("222222");};
 *	var funArray = [aa,bb];
 *	var btnText=["查询","增加"];
 *	var iconArray = ["icon-search","icon-add"];
 *	var idArray = ["testBtn_1","testBtn_2"];
 *	gridBtnObj.btnTextArray = btnText;
 *	gridBtnObj.iconArray = iconArray;
 *	gridBtnObj.funArray = funArray;
 *	gridBtnObj.btnIdArray = idArray;
 *	appendGridBtn("roleList",gridBtnObj);
 * 
 */
var gridBtnObj = {
	btnTextArray:null,//按钮文字
	iconArray:null,// 按钮图标
	funArray:null,//onclick事件 
	btnIdArray:null//按钮ID
};
function appendGridBtn(gridId,gridBtnObj){
	var list = $("#" + gridId + "_gridBody").html();
	$("#" + gridId + "_gridBody").empty();
	var btnTextHtml = "";
	if(gridBtnObj.btnTextArray && gridBtnObj.iconArray && gridBtnObj.btnIdArray){
		btnTextHtml +="<div style='height:25px;text-align:center;line-height:25px;margin-top:5px'>";
		for(var i = 0;i<gridBtnObj.btnTextArray.length;i++){
			btnTextHtml +="<a id='"+gridBtnObj.btnIdArray[i]+"_cbtn' href='javascript:void(0)' class='easyui-linkbutton l-btn' >";
			btnTextHtml +="<span class='l-btn-left'>";
			btnTextHtml +="<span class='l-btn-text "+gridBtnObj.iconArray[i]+" l-btn-icon-left'>"+gridBtnObj.btnTextArray[i]+"</span>";
			btnTextHtml +="</span>";
			btnTextHtml +="</a>&nbsp;&nbsp;&nbsp;&nbsp;";
		}
		btnTextHtml +="</div>";
	}
	$("#" + gridId + "_gridBody").html(list+btnTextHtml);
	if(gridBtnObj.funArray){
		for(var j = 0;j<gridBtnObj.funArray.length;j++){
			$("#"+gridBtnObj.btnIdArray[j]+"_cbtn").click(gridBtnObj.funArray[j]);
		}
	}
}

/**
 * JS 刷新首页
 * 
 * @since 1.0
 */
function refreshMainTab() {
	var currentTab = window.parent.$('#mainTab').tabs('getTab',
			I18N.mainPage.mainPage);
	var content = '<iframe scrolling="auto" frameborder="0" src="'
			+ webBasePath
			+ 'restManage/employeePage" width="100%" style="height:100%"></iframe>';
	window.parent.$('#mainTab').tabs('update', {
		tab : currentTab,
		options : {
			content : content
		}
	});
}

/**
 * 关闭指定标题或索引号的tab
 * 
 * @param tabTitle
 * @param tabIndex
 */
function closeTab(tabTitle, tabIndex) {
	if (tabTitle || tabIndex) {
		window.parent.$("#mainTab").tabs("close", tabTitle || tabIndex);
	}
}
/**
 * 获取一周日期时间
 */
function getWeekForDate(date,weekth){
	weekth = weekth || 6;
	var dayOfWeek = date.getDay();
	var sundayOffset = (dayOfWeek == 0) ? -6 : (1 - dayOfWeek);
	date.setDate(date.getDate() + sundayOffset);
	var dateFrom = myformatter(date);
	date.setDate(date.getDate() + weekth);
	var dateTo = myformatter(date); 
	return {from:dateFrom,to:dateTo};
}
/**
 * 格式化I18N消息
 * 
 * @param string
 * @returns
 */
function messageFormat(string) {
	var args = arguments;
	if (args.length > 1) {
		var pattern = new RegExp("{([0-" + (arguments.length - 2) + "])}", "g");
		return String(string).replace(pattern, function(match, index) {
			return args[parseInt(index) + 1];
		});
	}
	return string;
}
// 从url或指定url中获取参数值
function getQueryString(name, srchString) {
	var searchString = "";
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	if (srchString != null && srchString != "") {
		searchString = srchString;
	} else {
		searchString = window.location.search.substr(1);
	}
	var r = searchString.match(reg);
	if (r != null)
		return unescape(r[2]);
	return null;
}

// 从数组中移除一个指定对象
function removeFromArray(tempArray, obj) {
	var indexof = -1;
	var len = tempArray.length >>> 0;

	var from = 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0)
		from += len;

	// 是否是第一个元素标识
	var flag = false;
	for (; from < len; from++) {
		if (from in tempArray && tempArray[from] === obj) {
			indexof = from;
			if (from == 0) {
				flag = true;
			}
		}
	}
	// 如果是第一个元素，则indexof会是0，则使用标识flag
	if (indexof > 0 || flag) {
		tempArray.splice(indexof, 1);
		return true;
	}
	return false;
}

// 获取cookie值
WHUtil.getCookie = function(cName) {
	var cValue = document.cookie || "";
	if (cValue.length > 0) {
		var cStart = cValue.indexOf(" " + cName + "=");
		if (cStart == -1) {
			cStart = cValue.indexOf(cName + "=");
		}
		if (cStart == -1) {
			cValue = null;
		} else {
			cStart = cValue.indexOf("=", cStart) + 1;
			var cEnd = cValue.indexOf(";", cStart);
			if (cEnd == -1) {
				cEnd = cValue.length;
			}
			cValue = unescape(cValue.substring(cStart, cEnd));
		}
	}
	return cValue;
};
// 设置cookie值
WHUtil.setCookie = function(cName, value, exdays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + (exdays || 0));
	var cValue = escape(value)
			+ ((exdays == null) ? "" : ";expires=" + exdate.toUTCString());
	document.cookie = cName + "=" + (cValue+";path=/");
};
// 检测cookie是否存在
function checkCookie(cName) {
	var cValue = getCookie(cName);
	return cValue != null && cValue != "";
}
WHUtil.getProcessKey = function(processKey){
	var versionIndex = processKey.indexOf("-");
	return versionIndex > -1 ? processKey.substring(0,versionIndex) : processKey;
}

// /////////////////////////////////////////
// JSON对象转换为String
WHUtil.stringifyJSON = function(value) {
	if (typeof Date.prototype.toJSON !== 'function') {
		Date.prototype.toJSON = function(key) {
			return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-'
					+ f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate())
					+ 'T' + f(this.getUTCHours()) + ':'
					+ f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds())
					+ 'Z' : null;
		};
		String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(
				key) {
			return this.valueOf();
		};
	}
	var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, meta = {
		'\b' : '\\b',
		'\t' : '\\t',
		'\n' : '\\n',
		'\f' : '\\f',
		'\r' : '\\r',
		'"' : '\\"',
		'\\' : '\\\\'
	};

	function quote(string) {
		return '"'
				+ string.replace(escapable,
						function(a) {
							var c = meta[a];
							return typeof c === "string" ? c : "\\u"
									+ ("0000" + a.charCodeAt(0).toString(16))
											.slice(-4);
						}) + '"';
	}
	function f(n) {
		return n < 10 ? "0" + n : n;
	}
	function str(key, holder) {
		var i, v, len, partial, value = holder[key], type = typeof value;
		if (value && typeof value === "object"
				&& typeof value.toJSON === "function") {
			value = value.toJSON(key);
			type = typeof value;
		}
		switch (type) {
		case "string":
			return quote(value);
		case "number":
			return isFinite(value) ? String(value) : "null";
		case "boolean":
			return String(value);
		case "object":
			if (!value) {
				return "null";
			}
			switch (Object.prototype.toString.call(value)) {
			case "[object Date]":
				return isFinite(value.valueOf()) ? '"' + value.getUTCFullYear()
						+ "-" + f(value.getUTCMonth() + 1) + "-"
						+ f(value.getUTCDate()) + "T" + f(value.getUTCHours())
						+ ":" + f(value.getUTCMinutes()) + ":"
						+ f(value.getUTCSeconds()) + "Z" + '"' : "null";
			case "[object Array]":
				len = value.length;
				partial = [];
				for (i = 0; i < len; i++) {
					partial.push(str(i, value) || "null");
				}
				return "[" + partial.join(",") + "]";
			default:
				partial = [];
				for (i in value) {
					if (Object.prototype.hasOwnProperty.call(value, i)) {
						v = str(i, value);
						if (v) {
							partial.push(quote(i) + ":" + v);
						}
					}
				}
				return "{" + partial.join(",") + "}";
			}
		}
	}
	/**
	 * if (window.JSON && window.JSON.stringify) { return
	 * window.JSON.stringify(value); }
	 */
	return str("", {
		"" : value
	});
};
/**
 * 为数据添加一个原型方法，以判断指定对象是否存在于数组中
 * 
 * @param substr
 * @param start
 * @returns
 */
Array.prototype.indexOfArray = function(substr, start) {
	var ta, rt, d = '\0';
	if (start != null) {
		ta = this.slice(start);
		rt = start;
	} else {
		ta = this;
		rt = 0;
	}
	var str = d + ta.join(d) + d, t = str.indexOf(d + substr + d);
	if (t == -1) {
		return -1;
	}
	rt += str.slice(0, t).replace(/[^\0]/g, '').length;
	return rt;
};
//从数组中移除一个指定对象
WHUtil.removeFromArray = function(tempArray,obj){
	var indexof = -1;
	var len = tempArray.length >>> 0;

	var from = 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0) from += len;
	
	// 是否是第一个元素标识
	var flag = false;
	for (; from < len; from++) {
	    if (from in tempArray && tempArray[from] === obj){
	    	indexof = from;
	    	if(from  == 0){
	    		flag = true;
	    	}
	    }
	}
	// 如果是第一个元素，则indexof会是0，则使用标识flag
	if(indexof > 0 || flag){
		tempArray.splice(indexof,1);
		return true;
	}
	return false;
};

/**
 * 添加字符串的trim方法支持
 */
if(typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
		  return this.replace(/^\s+|\s+$/g, ''); 
	  };
}

/**
 * 屏蔽 backspace和enter 导致系统退出的问题
 */
$(document).keydown(function(e) {
	var doPrevent;
	if (e.keyCode == 8) {
		var d = e.srcElement || e.target;
		if (d.tagName.toUpperCase() == 'INPUT'
				|| d.tagName.toUpperCase() == 'TEXTAREA'
				|| d.tagName.toUpperCase() == 'SELECT') {
			doPrevent = d.readOnly || d.disabled;
		} else {
			doPrevent = true;
		}
	} else {
		doPrevent = false;
	}
	if (doPrevent) {
		e.preventDefault();
	}
});
/**
 * 解锁tab
 */
function enableTab(tabId){
//	var alltabsIndex = $('#'+tabId).tabs("tabs").length;
//	for(var i = 0;i<alltabsIndex ;i++){
//		$('#'+tabId).tabs('enableTab',i);
//	}
}
/**
 * 解锁父窗口tab
 */
function enableParentTab(tabId){
//	var alltabsIndex = window.parent.$('#'+tabId).tabs("tabs").length;
//	for(var i = 0;i<alltabsIndex ;i++){
//		window.parent.$('#'+tabId).tabs('enableTab',i);
//	}
}
/**
 * 加锁tab
 */
function disableTab(tabId,index){
//	var alltabsIndex = $('#'+tabId).tabs("tabs").length;
//	for(var i = 0;i<alltabsIndex ;i++){
//		if(i != index){
//			$('#'+tabId).tabs('disableTab',i);
//		}else{
//			$('#'+tabId).tabs('enableTab',i);
//		}
//	}
}
/**
 * 解锁父窗口tab
 */
function bindIframeOnloadSuccess(tabId,frameId){
//	var iframe = document.getElementById(frameId); 
//	if (iframe.attachEvent){ 
//		iframe.attachEvent("onload", function(){ 
//			enableTab(tabId);
//		});
//	}else{
//		iframe.onload = function(){ 
//			enableTab(tabId);
//		};
//	}
}
/**
 *iframe加载完成后解锁父窗口tabs 
 */
function bindIframeOnloadSuccessParent(tabId,frameId){
//	var iframe = window.parent.document.getElementById(frameId); 
//	if (iframe.attachEvent){ 
//		iframe.attachEvent("onload", function(){ 
//			enableParentTab(tabId);
//		});
//	}else{
//		iframe.onload = function(){ 
//			enableParentTab(tabId);
//		};
//	}
}
var changeCNAMoney = function(money)
{
    //debugger;
    var IntNum,PointNum,IntValue,PointValue,unit,moneyCNY;
    var Number  = "零壹贰叁肆伍陆柒捌玖";
    var NUMUnit = { LING : "零",SHI : "拾",BAI : "佰",QIAN : "仟",WAN : "万",YI : "亿" };
    var CNYUnit = { YUAN : "元",JIAO : "角",FEN : "分",ZHENG : "整" };
    var beforeReplace = 
    {
        Values :
        [
            {Name: NUMUnit.LING + NUMUnit.YI},               // 零亿
            {Name: NUMUnit.LING + NUMUnit.WAN},              // 零万
            {Name: NUMUnit.LING + NUMUnit.QIAN},             // 零千
            {Name: NUMUnit.LING + NUMUnit.BAI},              // 零百
            {Name: NUMUnit.LING + NUMUnit.SHI},              // 零十
            {Name: NUMUnit.LING + NUMUnit.LING},             // 零零
            {Name: NUMUnit.YI + NUMUnit.LING + NUMUnit.WAN}, // 亿零万
            {Name: NUMUnit.LING + NUMUnit.YI},               // 零亿
            {Name: NUMUnit.LING + NUMUnit.WAN},              // 零万
            {Name: NUMUnit.LING + NUMUnit.LING}              // 零零
        ]
    };
    var afterReplace = 
    {
        Values :
        [
            {Name: NUMUnit.YI + NUMUnit.LING}, //亿零
            {Name: NUMUnit.WAN + NUMUnit.LING},//万零
            {Name: NUMUnit.LING},              //零
            {Name: NUMUnit.LING},              //零
            {Name: NUMUnit.LING},              //零
            {Name: NUMUnit.LING},              //零
            {Name: NUMUnit.YI + NUMUnit.LING}, //亿零
            {Name: NUMUnit.YI},                //亿
            {Name: NUMUnit.WAN},               //万
            {Name: NUMUnit.LING}               //零
        ]
    };
    var pointBefore = 
    {
        Values :
        [
            {Name: NUMUnit.LING + CNYUnit.JIAO}, //零角
            {Name: NUMUnit.LING + CNYUnit.FEN},  //零分
            {Name: NUMUnit.LING + NUMUnit.LING}, //零零
            {Name: CNYUnit.JIAO + NUMUnit.LING}  //角零
        ]
    };
    var pointAfter = 
    {
        Values :
        [
            {Name: NUMUnit.LING}, //零
            {Name: NUMUnit.LING}, //零
            {Name: ""},
            {Name: CNYUnit.JIAO}  //角
        ]
    };
    
    /// 递归替换
    var replaceAll = function(inputValue,beforeValue,afterValue)
    {
        while(inputValue.indexOf(beforeValue) > -1)
        {
            inputValue = inputValue.replace(beforeValue,afterValue);
        }
        return inputValue;
    };
    /// 获取输入金额的整数部分
    IntNum = money.indexOf(".") > -1 ? money.substring(0,money.indexOf(".")) : money;
    /// 获取输入金额的小数部分
    PointNum = money.indexOf(".") > -1 ? money.substring(money.indexOf(".")+1) : "";
    IntValue = PointValue = "";
    
    /// 计算整数部分
    for(var i=0;i<IntNum.length;i++)
    {
        /// 获取数字单位
        switch((IntNum.length-i) % 8)
        {
            case 5:
                unit = NUMUnit.WAN; //万
                break;
            case 0:
            case 4:
                unit = NUMUnit.QIAN; //千
                break;
            case 7:
            case 3:
                unit = NUMUnit.BAI; //百
                break;
            case 6:
            case 2:
                unit = NUMUnit.SHI; //十
                break;
            case 1:
                if((IntNum.length-i) > 8)
                {
                    unit = NUMUnit.YI; //亿    
                }
                else { unit = ""; }
                break;
            default:
                unit = "";
                break;
        }
        /// 组成整数部分
        IntValue += Number.substr(parseInt(IntNum.substr(i,1)),1) + unit;
    }
    
    /// 替换零
    for(var i=0;i<beforeReplace.Values.length;i++)
    {
        IntValue = replaceAll(IntValue,beforeReplace.Values[i].Name,afterReplace.Values[i].Name);             
    }
    // 末尾是零则去除
    if(IntValue.substr(IntValue.length-1,1) == NUMUnit.LING){
   		IntValue = IntValue.substring(0,IntValue.length-1);
    }
    // 一十开头的替换为十开头
    if(IntValue.substr(0,2) == Number.substr(1,1) + NUMUnit.SHI) IntValue = IntValue.substr(1,IntValue.length-1);
    
    /// 计算小数部分
    if(PointNum != "")
    {
        PointValue = Number.substr(PointNum.substr(0,1),1) + CNYUnit.JIAO;
        PointValue += Number.substr(PointNum.substr(1,1),1) + CNYUnit.FEN;
        for(var i=0;i<pointBefore.Values.length;i++)
        {
            PointValue = replaceAll(PointValue,pointBefore.Values[i].Name, pointAfter.Values[i].Name);
        }
    }
    moneyCNY = PointValue == "" ? (IntValue.length > 0 ? (IntValue + CNYUnit.YUAN + CNYUnit.ZHENG) : (NUMUnit.LING + CNYUnit.YUAN + CNYUnit.ZHENG)) : (IntValue.length > 0 ? (IntValue + CNYUnit.YUAN + PointValue) : ( NUMUnit.LING + CNYUnit.YUAN + PointValue));
    return moneyCNY;
};

function openDoc(url){
	var openDocObj  = new ActiveXObject("SharePoint.OpenDocuments.2"); 
	var path = serverPathUpload+url;
	openDocObj.ViewDocument(path);   
}

//计算两个日期之差
function DateDiff(d1,d2){
   var day = 24 * 60 * 60 *1000;
   try{    
        var dateArr = d1.split("-");
        var checkDate = new Date();
        checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
        var checkTime = checkDate.getTime();
        var dateArr2 = d2.split("-");
        var checkDate2 = new Date();
        checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
        var checkTime2 = checkDate2.getTime();
    
        var cha = (checkTime - checkTime2)/day;  
        return cha;
    }catch(e){
        return false;
    }
}
//将string转换为Date
//str必须满足如下格式: 2008-04-29
function convertString2Date(str) {
	//用户split分隔出数组,将包含3个元素:年,月,日
	var splitArray = str.split("-");
	// 用年,月,日构造日期对象
	// splitArray[0]-> year, splitArray[1]-> month, splitArray[2]->day
	// 这时要注意月份是从0开始的
	var date = new Date(splitArray[0], splitArray[1] - 1, splitArray[2]);
	return date;
}

// 得到date1和date2之间的间隔
// date2要比date1大
// date要满足如下格式: 2008-04-29
// 参数date1和date2类型应该是String或Date
// 确保两种类型没有问题
function getIntervalBetweenTwoDates(date1, date2) {
	var realDate1 = date1;
	var realDate2 = date2;
	// 如果date1是Date类型就不用转换
	if (!(date1 instanceof Date)) {
		realDate1 = convertString2Date(date1);
	}
	// 如果date2是Date类型就不用转换
	if (!(date2 instanceof Date)) {
		realDate2 = convertString2Date(date2);
	}
	//得到绝对值,(realDate2.getTime() - realDate1.getTime())返回的是毫秒所以要先除1000
	var interval = Math.abs((realDate2.getTime() - realDate1.getTime()))/(1000 * 60 * 60 * 24);
	return interval;
}
/**
 * 返回两日期间的工作日数
 * @param date1 开始时间
 * @param date2 结束事件
 * @returns {Number}
 */
function listAllDatesBetweenTwoDates(date1,date2) {
	var working =0;
	var interval = getIntervalBetweenTwoDates(date1, date2);
	// 转换string为Date
	date1 = convertString2Date(date1);
	var year = date1.getFullYear();
	var month = date1.getMonth();
	var date = date1.getDate();
	for ( var i = 0; i <= interval; ++i) {
		var theDate = new Date(year, month, date);
		var day = theDate.getDay();
		if (0 == day || 6 == day){
			working ++;
		}
		date++;
	}
	return interval-working+1;
}


String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {  
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {  
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);  
    } else {  
        return this.replace(reallyDo, replaceWith);  
    }  
};
